﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HZY.Logic.Sys
{
    using System.Linq;
    using System.Threading.Tasks;
    using System.Collections;
    using HZY.DbExtensions;
    using HZY.Models.Sys;
    using HZY.Models;
    using HZY.Toolkit;
    using HZY.DTO.Sys;
    using HZY.Logic.Core;
    using HzySql.Interface;

    public class Sys_FunctionLogic : LogicBase
    {

        public Sys_FunctionLogic(HzySqlDbContext dbContext)
            : base(dbContext)
        {

        }


        #region CURD 基础

        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <param name="Page"></param>
        /// <param name="Rows"></param>
        /// <param name="Search"></param>
        /// <returns></returns>
        public async Task<TableViewModel> FindListAsync(int Page, int Rows, Sys_Function Search)
        {
            var query = db.Query<Sys_Function>()
                .Where(w => w.t1.Function_Name.Contains(Search.Function_Name), !string.IsNullOrWhiteSpace(Search.Function_Name))
                .Select(w => new
                {
                    w.t1.Function_Num,
                    w.t1.Function_Name,
                    w.t1.Function_ByName,
                    w.t1.Function_CreateTime,
                    _ukid = w.t1.Function_ID
                })
                .TakePage(Page, Rows, out int TotalCount)
                ;

            return await this.db.AsTableViewModelAsync(query, Page, Rows, TotalCount);
        }

        /// <summary>
        /// 新增\修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Guid> SaveAsync(Sys_Function model)
        {
            if (model.Function_ID == Guid.Empty)
            {
                model.Function_ID = await db.Insert(model).SaveAsync<Guid>();
            }
            else
            {
                await db.UpdateById(model).SaveAsync();
            }

            return model.Function_ID;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Keys"></param>
        /// <returns></returns>
        public async Task DeleteAsync(List<Guid> Ids)
        {
            this.iSqlContexts = new List<ISqlContext>();

            foreach (var item in Ids)
            {
                db.Delete<Sys_Function>(w => w.t1.Function_ID == item).ToSqlContext(this.iSqlContexts);
            }

            //此函数用于批量 sql 操作
            await db.ExecuteBatchAsync(this.iSqlContexts);
        }

        /// <summary>
        /// 加载表单 数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<object> LoadFormAsync(Guid Id)
        {
            var Model = await db.FindByIdAsync<Sys_Function>(Id);

            return new { Id, Model };
        }


        #endregion






    }
}
